package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
)

var FileInfo = &cobra.Command{
	Use:     "file_info",
	Short:   "文件信息",
	Long:    "文件信息",
	Example: "file_info --path=./data",
	Run: func(cmd *cobra.Command, args []string) {
		var (
			count int64
			size  int64
		)
		if File == "" {
			fmt.Println("请输入文件路径:--file=data或-f=data")
			return
		}
		GetPathInfo(File, &count, &size)
		path, _ := filepath.Abs(File)
		fmt.Printf("%s 文件大小：%db，文件数量：%d\n", path, size, count)
	},
}

var (
	File string
)

func init() {
	RootCmd.AddCommand(FileInfo)
	FileInfo.Flags().StringVarP(&File, "file", "f", "", "文件路径")
}

func GetPathInfo(file string, count, size *int64) {
	pathInfo, err := os.Stat(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	if !pathInfo.IsDir() {
		*size = pathInfo.Size()
		*count++
		return
	}

	list, err := os.ReadDir(file)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, v := range list {
		info, _ := v.Info()
		*count++
		*size += info.Size()
		if info.IsDir() {
			GetPathInfo(file+"/"+v.Name(), count, size)
		}
	}
}
